/**
 * @description 工具集
 * @author c-jw
 * @time 2020年3月31日 15:05:49
 */

/**
 * @desc 全屏
 */
export const fullScreen = function (el) {
  el = el || document.body;
  let requestFullscreen =
    el.requestFullscreen ||
    el.mozRequestFullScreen ||
    el.webkitRequestFullscreen ||
    el.msRequestFullscreen;
  if (requestFullscreen) {
    requestFullscreen();
  } else {
    alert("当前浏览器不支持全屏");
  }
};
/**
 * @desc 退出全屏
 */
export const exitFullscreen = function () {
  let exitFullscreen =
    document.exitFullscreen ||
    document.mozCancelFullScree ||
    document.webkitExitFullscreen ||
    document.webkitExitFullscreen;
  if (exitFullscreen) {
    exitFullscreen();
  } else {
    alert("当前浏览器不支持退出全屏");
  }
};
/**
 * @desc 随机名称
 */
export const makeRandomName = function (name = "") {
  const add0 = (m) => {
    return m < 10 ? "0" + m : m;
  };
  const timestamp = () => {
    var time = new Date();
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    var mills = time.getMilliseconds();

    return `${y}${add0(m)}${add0(d)}${add0(h)}${add0(mm)}${add0(s)}${mills}`;
  };
  return `${name}_${Math.round(Math.random() * 1000)}_${timestamp()}`;
};
/**
 * @desc 日期格式化
 */
export const dateFormat = function (time, fmt) {
  var date = new Date(time);
  fmt = fmt || "YYYY-MM-DD HH:mm:ss ";
  var o = {
    "M+": date.getMonth() + 1, //月份
    "D+": date.getDate(), //日
    "H+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds() //毫秒
  };
  if (/(Y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};
/**
 * @desc 阻止事件冒泡
 */
export const preventEvent = function (ev) {
  ev.preventDefault();
  ev.stopPropagation();
};

export const numberStr = function (value, point, withPoint) {
  var num = 0;
  if (value >= Math.pow(10, 12)) {
    //兆
    num = value / Math.pow(10, 12);
    unit = "兆";
  } else if (value >= Math.pow(10, 8)) {
    //亿
    num = value / Math.pow(10, 8);
    unit = "亿";
  } else if (value >= Math.pow(10, 4)) {
    // 万;
    num = value / Math.pow(10, 4);
    unit = "万";
  } else {
    num = value;
  }
  //  num = value / Math.pow(10, 4);
  var unit = "";
  var numArr = ((num || 0) + "").split("e");
  var power = numArr[1];
  var arr = (numArr[0] || "").split(".");

  if (point > 0) {
    withPoint && (arr[1] = new String(arr[1] || "").padEnd(point, "0"));
    arr[1] && (arr[1] = arr[1].substring(0, point));
  } else if (!point) {
    // arr = [arr[0]];
  }
  var val = arr.join(".");
  var result = (power ? val + "e" + power : val) + unit;
  // console.log(result, value, num, numArr, arr);
  return result;
};
export const tranNumber = function (value, point, withPoint) {
  var unit = "";
  var num = 0;
  if (value >= Math.pow(10, 16)) {
    //万兆
    num = value / Math.pow(10, 16);
    unit = "万兆";
    num = value;
    unit = "";
  } else if (value >= Math.pow(10, 12)) {
    //兆
    num = value / Math.pow(10, 12);
    unit = "兆";
  } else if (value >= Math.pow(10, 8)) {
    //亿
    num = value / Math.pow(10, 8);
    unit = "亿";
  } else if (value >= Math.pow(10, 4)) {
    // 万;
    num = value / Math.pow(10, 4);
    unit = "万";
  } else {
    num = value;
  }
  var numArr = ((num || 0) + "").split("e");
  var power = numArr[1];

  var arr = (numArr[0] || "").split(".");

  if (point > 0) {
    withPoint && (arr[1] = new String(arr[1] || "").padEnd(point, "0"));
    arr[1] && (arr[1] = arr[1].substring(0, point));
  } else if (!point) {
    arr = [arr[0]];
  }
  var val = arr.join(".");
  var result = (power ? val + "e" + power : val) + unit;
  console.log(result, value, num, numArr, arr);
  return result;
};

export const formatNum = function (value) {
  if (!value && value !== 0) return 0;
  let str = value.toString();
  let reg = str.indexOf(".") > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g;
  return str.replace(reg, "$1,");
};
/**
 * @desc 数字格式化
 */
export const tranNumber1 = function (num = 0, point) {
  // let str = num + "";
  // return str;
  // 将数字转换为字符串,然后通过split方法用.分隔,取到第0个
  let numStr = ((num || 0) + "").split(".")[0];
  if (numStr.length < 6) {
    // 判断数字有多长,如果小于6,,表示10万以内的数字,让其直接显示
    // console.log(numStr);
    return numStr;
  } else if (numStr.length >= 6 && numStr.length <= 16) {
    // 如果数字大于6位,小于8位,让其数字后面加单位万
    let decimal = numStr.substring(numStr.length - 4, numStr.length - 4 + point);
    // console.log(decimal);
    // 由千位,百位组成的一个数字
    return parseFloat(Math.floor(num / 10000) + "." + decimal) + "万";
  } else if (numStr.length > 12) {
    // 如果数字大于8位,让其数字后面加单位亿
    let decimal = numStr.substring(numStr.length - 12, numStr.length - 12 + point);
    // console.log(decimal);
    return parseFloat(parseInt(num / 1000000000000) + "." + decimal) + "兆";
  } else if (numStr.length > 8) {
    // 如果数字大于8位,让其数字后面加单位亿
    let decimal = numStr.substring(numStr.length - 8, numStr.length - 8 + point);
    // console.log(decimal);
    return parseFloat(parseInt(num / 100000000) + "." + decimal) + "亿";
  }
};
/**
 * @desc uuid
 */

export const uuid = function uuid(len = 32) {
  function byteArrayToBase64(uint8) {
    var lookup = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
      extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
      output = "",
      temp,
      length,
      i;

    function tripletToBase64(num) {
      return (
        lookup[(num >> 18) & 0x3f] +
        lookup[(num >> 12) & 0x3f] +
        lookup[(num >> 6) & 0x3f] +
        lookup[num & 0x3f]
      );
    }

    // go through the array every three bytes, we'll deal with trailing stuff later
    for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
      temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
      output += tripletToBase64(temp);
    }

    // pad the end with zeros, but make sure to not forget the extra bytes
    switch (extraBytes) {
      case 1:
        temp = uint8[uint8.length - 1];
        output += lookup[temp >> 2];
        output += lookup[(temp << 4) & 0x3f];
        output += "==";
        break;
      case 2:
        temp = (uint8[uint8.length - 2] << 8) + uint8[uint8.length - 1];
        output += lookup[temp >> 10];
        output += lookup[(temp >> 4) & 0x3f];
        output += lookup[(temp << 2) & 0x3f];
        output += "=";
        break;
    }

    return output;
  }
  function randomBytes(size) {
    var bytes = new Array(size);
    var r;

    for (var i = 0, r; i < size; i++) {
      if ((i & 0x03) == 0) r = Math.random() * 0x100000000;
      bytes[i] = (r >>> ((i & 0x03) << 3)) & 0xff;
    }

    return bytes;
  }

  return byteArrayToBase64(randomBytes(Math.ceil(Math.max(8, len * 2))))
    .replace(/[+\/]/g, "")
    .slice(0, len);

  // var temp_url = URL.createObjectURL(new Blob());
  // var uuid = temp_url.toString();
  // return uuid.substring(uuid.lastIndexOf("/") + 1);
};
/**
 * @desc 字节格式化
 */
export const bytesToSize = function (bytes = 0) {
  // console.log(bytes);
  if (bytes === 0) return "0 B";
  var k = 1024;
  let sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  let i = Math.floor(Math.log(bytes) / Math.log(k)); //return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
  return Number((bytes / Math.pow(k, i)).toPrecision(3)) + " " + sizes[i]; //toPrecision(3) 后面保留两位小数，如1.00GB
};

/**
 * @desc 个性日志
 */
export const log = function (o) {
  console.log("%c %s %O", "color:red", "[连接数据库失败]", o);
};

/**
 * @desc 路由前进后退
 * @param  current <int> 前进后退步伐
 * @param  defaultUrl <String>window.history.state为空时(当前页面没有上级路由历史)跳转到默认路径
 * @example routerGo(-1,'/home');
 */
export const routerGo = function (current, defaultUrl) {
  var state = window.history.state;
  if ((!state || !state.back) && defaultUrl != null) {
    return (location.hash = defaultUrl);
  }
  window.history.go(current);
};
